package com.mas.admin.biz.dal.redis.oauth2;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.mas.admin.biz.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.mas.admin.biz.dal.redis.RedisKeyConstants.OAUTH2_ACCESS_TOKEN;

/**
 * @author godyao
 * @description {@link OAuth2AccessTokenDO} 的 redis 持久层操作
 * @date 2023年02月13日17:02
 */
@Repository
public class OAuth2AccessTokenRedisDAO {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate<String, OAuth2AccessTokenDO> redisTemplate;

    public OAuth2AccessTokenDO get(String accessToken) {
        String redisKey = formatKey(accessToken);
        return redisTemplate.opsForValue().get(redisKey);
    }

    public void set(OAuth2AccessTokenDO accessTokenDO) {
        final String redisKey = formatKey(accessTokenDO.getAccessToken());
        accessTokenDO.setUpdater(null).setCreator(null).setCreateTime(null).setUpdateTime(null).setDeleted(null);
        final long expireTime = LocalDateTimeUtil.between(LocalDateTime.now(), accessTokenDO.getExpiresTime(), ChronoUnit.SECONDS);
        redisTemplate.opsForValue().set(redisKey, accessTokenDO, expireTime, TimeUnit.SECONDS);
    }

    public void delete(String accessToken) {
        String redisKey = formatKey(accessToken);
        redisTemplate.delete(redisKey);
    }

    public void deleteList(Collection<String> accessTokens) {
        List<String> redisKeys = accessTokens.stream().map(OAuth2AccessTokenRedisDAO::formatKey).collect(Collectors.toList());
        redisTemplate.delete(redisKeys);
    }

    public void deleteList0(Collection<OAuth2AccessTokenDO> accessTokens) {
        List<String> redisKeys = accessTokens.stream().map(OAuth2AccessTokenRedisDAO::formatKey0).collect(Collectors.toList());
        redisTemplate.delete(redisKeys);
    }

    private static String formatKey(String accessToken) {
        return String.format(OAUTH2_ACCESS_TOKEN.getKeyTemplate(), accessToken);
    }

    private static String formatKey0(OAuth2AccessTokenDO accessToken) {
        return formatKey(accessToken.getAccessToken());
    }
}
